#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
class tcp_Client
{
public:
    tcp_Client(string Serverip, uint16_t Serverport) : _Serverip(Serverip), _Serverport(Serverport)
    {
    }
    ~tcp_Client()
    {
    }
    void Init()
    {
        // 创建socket
        _socketfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_socketfd == -1)
        {
            cerr << "Client err" << errno << strerror(errno) << endl;
            exit(2);
        }
    }
    void run()
    {
        struct sockaddr_in peer;
        peer.sin_addr.s_addr = inet_addr(_Serverip.c_str());
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_Serverport);
        socklen_t len = sizeof(peer);
        if (connect(_socketfd, (struct sockaddr *)&peer, len) != 0)
        {
            cout << "connnet error" << endl;
            exit(2);
        }
        string message;
        char buffer[1024];

        while (1)
        {
            cout << "plase Enter# ";
            getline(cin, message);
            int n = write(_socketfd, message.c_str(), message.size());
            if (n < 0)
            {
                cout << "write error" << endl;
                exit(2);
            }
            int i = read(_socketfd, buffer, sizeof buffer);
            if (i < 0)
            {
                cout << "read error" << endl;
                exit(2);
            }
            else if (i>0)
            {
                buffer[i] = 0;
                cout << "Server 回显::" << buffer << endl;
            }
        }
    }

private:
    int _socketfd;
    string _Serverip;
    uint16_t _Serverport;
};